<template>
	<view>
		<view class="wapper">
			<swiper :duration="100" @change='currentChange' :current="activeIndex" previous-margin="150rpx"
				next-margin="150rpx">
				<swiper-item v-for="i in [0,1]" :key='i'>
					<view class="swiper-item" :class="activeIndex == i ?'active':'noActive'">
						<image class="share_image" :src="IMGLink +'/index/poster-share'+(i+1)+'.png'" mode="widthFix">
						</image>
						<view class="item_center">
							<view class="item_left">
								<view class="item_left_logo">
									<image :src="logo" mode="widthFix"></image>
									<text>天下竞品会员</text>
								</view>
								<view class="item_left_text">
									<view>扫码邀请好友</view>
									<view>更多好礼等着你</view>
								</view>
							</view>
							<view class="item_right">
								<image :src="codeUrl" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="footer" :style="{justifyContent:IS_WEIXIN?'space-between':'center'}">
			<view class="item" v-if="IS_WEIXIN">
				<button open-type="share">
					<view class="image_box">
						<image :src="IMGLink+'/index/weixin.png'" mode="widthFix"></image>
					</view>
					<view class="text">
						微信
					</view>
				</button>
			</view>
			<view class="item" @click="save">
				<view class="image_box">
					<image :src="IMGLink+'/index/dowload.png'" mode="widthFix"></image>
				</view>
				<view class="text">
					保存图片
				</view>
			</view>
		</view>
		<canvas style="width: 896rpx; height: 1584rpx;position: fixed;left:-9999px; top: -9999px;"
			:style="scale?'transform: scale(.5);':''" canvas-id="canvas" id="canvas"></canvas>
		<uni-popup ref="popup" :animation="true" style="width: 100%;">
			<view class="imgbox" style="width: 504rpx;height: 900rpx;">
				<image :src="shareImgData" style="width: 100%;height: 100%;"></image>
			</view>
			<view class="share_tips">长按图片保存至相册</view>
			<image class="close" @click.stop="_close" src="../../../static/image/common/close.png" ></image>
		</uni-popup>
	</view>
</template>

<script>
	import {
		createqrcode
	} from '@/api/shopping/shopping'
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				IMGLink: this.IMGLink,
				logo: this.IMGLink + '/index/logo.png',
				activeIndex: 0,
				cWidth: 0,
				cHeight: 0,
				scale: false,
				codeData: null,
				codeUrl: null,
				IS_WEIXIN: false,
				shareImgData: null
			}
		},
		computed: {
			...mapState(['userinfo'])
		},
		onLoad() {
			//#ifdef MP-WEIXIN
			this.IS_WEIXIN = true;
			//#endif
			createqrcode({
				// page: '/pages/index/home/index',
				scene: 'invitationcode=' + this.userinfo.invitation_code
			}).then(({
				data: {
					url
				}
			}) => {
				this.codeUrl = url;
				if (this.IS_WEIXIN) {
					this.getCodePath(url).then(res => {
						this.codeData = res;
					})
				}
			})
		},
		onReady() {
			wx.createSelectorQuery()
				.in(this)
				.select("#canvas")
				.fields({
					node: true,
					size: true,
				}).exec((res) => {
					this.cWidth = res[0].width;
					this.cHeight = res[0].height;
				})
			setTimeout(() => {
				this.scale = true;
			}, 100)
		},
		methods: {
			_close(){
				this.$refs.popup.close()
			},
			getCodePath(codeData) {
				const [save, number] = [wx.getFileSystemManager(), Math.random()];
				const path = wx.env.USER_DATA_PATH + '/pic' + number + '.png';
				return new Promise((r, j) => {
					save.writeFile({
						filePath: path,
						data: codeData.slice(22),
						encoding: 'base64',
						success: res => {
							r(path)
						},
						fail: err => {
							j()
							console.log(err)
						}
					})
				})
			},
			save() {
				const {
					IS_WEIXIN,
				} = this;
				if (this.IS_WEIXIN) {
					this.wxSavePic()
				} else {
					this.webSavePic()
				}
			},
			async webSavePic() {
				const {
					codeUrl,
				} = this;
				if (codeUrl) {
					uni.showLoading({
						title: '请等待图片生成',
						mask: true
					})
					try {
						const {
							activeIndex,
							cWidth,
							cHeight,
							logo,
							proportion: ptn
						} = this;
						const pic = '../../../static/image/index/shareImg/poster-share' + (activeIndex + 1) + '.png';
						const ctx = uni.createCanvasContext('canvas', this);
						ctx.drawImage(pic, 0, 0, cWidth, cHeight);
						ctx.save()

						ctx.setFillStyle('#FFFFFF')
						ctx.fillRect(ptn(22, 'w'), ptn(596, 'h'), ptn(406, 'w'), ptn(154, 'h'));
						ctx.save()

						ctx.drawImage('../../../static/image/index/shareImg/logo.png', ptn(42, 'w'), ptn(612, 'h'),
							ptn(40, 'w'), ptn(40, 'w'));
						ctx.save()

						ctx.drawImage(codeUrl, ptn(284, 'w'), ptn(612, 'h'), ptn(124, 'w'), ptn(124, 'w'));
						ctx.save()

						ctx.setFillStyle('#202223')
						ctx.setFontSize(ptn(20, 'h'))
						ctx.fillText('天下竞品会员', ptn(92, 'w'), ptn(640, 'h'))

						ctx.setFillStyle('#3A3A3A');
						ctx.setFontSize(ptn(21, 'h'));
						ctx.fillText('扫码邀请好友', ptn(42, 'w'), ptn(688, 'h'));
						ctx.fillText('更多好礼等着你', ptn(42, 'w'), ptn(718, 'h'));
						ctx.draw(true, () => {
							uni.canvasToTempFilePath({
								canvasId: 'canvas',
								success: (res) => {
									uni.hideLoading();
									this.shareImgData = res.tempFilePath;
									this.$nextTick(() => {
										this.$refs.popup.open('center');
									})
								},
								fail: (err) => {
									uni.hideLoading();
									uni.showToast({
										title: '加载失败',
										icon: 'none',
										duration: 2000
									});
								}
							}, this);
						});
					} catch (e) {
						console.log(e)
						uni.hideLoading()
					}
				} else {
					uni.showToast({
						title: '稍等片刻，正在获取数据',
						icon: 'none'
					})
				}
			},
			downloadPic(dataurl) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				const blobData = new Blob([u8arr], {
					type: mime
				});
				const a = document.createElement("a");
				a.href = URL.createObjectURL(blobData);
				a.download = 'share'; // 下载文件的名字
				document.body.appendChild(a);
				a.click();
			},
			async wxSavePic() {
				const {
					codeData,
				} = this;
				if (codeData) {
					uni.showLoading({
						title: '请等待图片生成',
						mask: true
					})
					try {
						const {
							activeIndex,
							cWidth,
							cHeight,
							logo,
							proportion: ptn
						} = this;
						const pic = this.IMGLink + '/index/poster-share' + (activeIndex + 1) + '.png';
						const ctx = uni.createCanvasContext('canvas', this);
						const imgs = await this.loadImgs([pic, logo, codeData]);
						ctx.drawImage(imgs[0], 0, 0, cWidth, cHeight);
						ctx.save()

						ctx.setFillStyle('#FFFFFF')
						ctx.fillRect(ptn(22, 'w'), ptn(596, 'h'), ptn(406, 'w'), ptn(154, 'h'));
						ctx.save()

						ctx.drawImage(imgs[1], ptn(42, 'w'), ptn(612, 'h'), ptn(40, 'w'), ptn(40, 'w'));
						ctx.save()

						ctx.drawImage(imgs[2], ptn(284, 'w'), ptn(612, 'h'), ptn(124, 'w'), ptn(124, 'w'));
						ctx.save()

						ctx.setFillStyle('#202223')
						ctx.setFontSize(ptn(20, 'h'))
						ctx.fillText('会员', ptn(92, 'w'), ptn(640, 'h'))

						ctx.setFillStyle('#3A3A3A');
						ctx.setFontSize(ptn(21, 'h'));
						ctx.fillText('扫码邀请好友', ptn(42, 'w'), ptn(688, 'h'));
						ctx.fillText('更多好礼等着你', ptn(42, 'w'), ptn(718, 'h'));
						ctx.draw(true, () => {
							uni.canvasToTempFilePath({
								canvasId: 'canvas',
								success: (res) => {
									this.saveImg(res.tempFilePath)
								},
								fail: (err) => {
									console.log(err)
									uni.hideLoading();
									uni.showToast({
										title: '加载失败',
										icon: 'none',
										duration: 2000
									});
								}
							}, this);
						});
					} catch (e) {
						console.log(e)
						uni.hideLoading()
					}
				} else {
					uni.showToast({
						title: '稍等片刻，正在获取数据',
						icon: 'none'
					})
				}
			},
			saveImg(path) {
				uni.saveImageToPhotosAlbum({
					filePath: path,
					success: () => {
						uni.hideLoading();
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						})
					},
					fail: () => {
						uni.hideLoading();
						uni.getSetting({
							success: res => {
								if (!res.authSetting['scope.writePhotosAlbum']) {
									uni.showModal({
										title: '提示',
										content: '保存图片需要使用您的相册权限',
										cancelText: '拒绝',
										confirmText: '去授权',
										success: res => {
											if (res.confirm) {
												uni.openSetting()
											} else {
												uni.showToast({
													title: '无法保存图片',
													icon: 'none'
												})
											}
										}
									})
								}
							}
						})
					}
				})
			},
			proportion(px, type) {
				const wh = {
					w: this.cWidth,
					h: this.cHeight,
				}
				const proportion = {
					w: 448,
					h: 792
				}
				return wh[type] * (px / proportion[type])
			},
			loadImgs(imgs) {
				return new Promise((wpr) => {
					let pArr = []
					imgs.forEach(e => {
						pArr.push(new Promise((r) => {
							uni.getImageInfo({
								src: e,
								success: res => {
									r(res.path)
								},
								fail: err => {
									console.log(err)
								}
							})
						}))
					})
					Promise.all(pArr).then(imgs => {
						wpr(imgs)
					})
				})
			},
			currentChange({
				detail: {
					current
				}
			}) {
				this.activeIndex = current
			}
		},
		onShareAppMessage() {
			return {
				title: '拼团购',
				path: '/pages/index/home/index?scene=invitationcode=' + this.userinfo.invitation_code
			}
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #EFF0F1;
	}
</style>
<style scoped>
	swiper {
		margin: 0 auto;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 20rpx;
		font-weight: 400;
		color: #3A3A3A;
		line-height: 26rpx;
	}

	.item_left_text {
		font-size: 20rpx;
	}

	.item_left_logo {
		margin-bottom: 18rpx;
		font-weight: 400;
		color: #3A3A3A;
		line-height: 26rpx;
		display: flex;
		align-items: center;
	}

	.item_left_logo>image {
		display: inline-block;
		width: 40rpx;
		height: 40rpx;
		border-radius: 5rpx;
		margin-right: 10rpx;
		font-size: 17rpx;
		font-weight: 400;
		color: #202223;
		align-items: center;
	}

	.item_left {
		display: flex;
		flex-direction: column;

	}

	.item_right {
		width: 124rpx;
		height: 124rpx;
		overflow: hidden;
	}

	swiper-item {
		display: flex;
		align-items: center;
	}

	.swiper-item {
		flex-shrink: 0;
		width: 448rpx;
		height: 792rpx;
		margin: 0 auto;
		position: relative;
		transition: all .3s;
	}

	.item_center {
		width: 406rpx;
		height: 154rpx;
		background: #FFFFFF;
		position: absolute;
		left: 50%;
		margin-left: -203rpx;
		bottom: 42rpx;
		box-sizing: border-box;
		padding: 16rpx 20rpx 26rpx 20rpx;
		display: flex;
		justify-content: space-between;
	}

	.active {
		transform: scale(1);
	}

	.noActive {
		transform: scale(.8);
	}

	@keyframes active {
		from {
			transform: scale(0.8);
		}

		to {
			transform: scale(1);
		}
	}

	@keyframes noActive {
		from {
			transform: scale(1);
		}

		to {
			transform: scale(.8);
		}
	}

	.wapper {
		height: calc(100vh - 204rpx);
	}

	.image_box {
		width: 104rpx;
		height: 104rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
	}

	image {
		display: block;
		width: 100%;
	}

	.share_image {
		display: block;
		width: 100%;
		height: 100% !important;
	}

	.footer {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 204rpx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 0 142rpx;
	}

	.item {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
	}


	button {
		position: relative;
		display: block;
		margin-left: auto;
		margin-right: auto;
		padding-left: 0;
		padding-right: 0;
		box-sizing: border-box;
		font-size: inherit;
		text-align: center;
		text-decoration: none;
		line-height: normal;
		border-radius: 0px;
		-webkit-tap-highlight-color: transparent;
		overflow: hidden;
		color: inherit;
		background-color: inherit;
	}

	button::after {
		border: 0;
	}

	button[disabled] {
		background-color: transparent;
		color: transparent;
	}

	.button-hover {
		color: rgba(0, 0, 0, 0);
		background-color: transparent;
	}

	.share_tips {
		text-align: center;
		color: white;
		margin-top: 40rpx;
		font-size: 40rpx;
	}
	.close{
		width: 60rpx;
		height: 60rpx;
		position: absolute;
		top: -60rpx;
		right: -60rpx;
	}
</style>
